package com.yygo.dao.hibernate;

import com.yygo.dao.ProvinceDao;
import com.yygo.model.City;
import com.yygo.model.Province;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by tiansha on 2015/6/24.
 */
@Repository("provinceDao")
public class ProvinceDaoHibernate extends GenericDaoHibernate<Province, Long> implements ProvinceDao {

    public ProvinceDaoHibernate() {
        super(Province.class);
    }

    @Override
    public void clearAll() {
        List<Province> provinces = getAll();
        for (Province province : provinces) {
            remove(province);
        }
    }

    @Override
    public List<City> findByProvinceName(String provinceName) {
        List provinces = getSession().createCriteria(Province.class).add(Restrictions.eq("name", provinceName)).list();
        if (provinces.size() == 0) {
            return new ArrayList<>();
        }
        Province province = (Province)provinces.get(0);
        List<City> list = province.getCities();
        return list;
    }

    @Override
    public String getProvinceNameByCode(String code) {
        Object object = getSession().createCriteria(Province.class).add(Restrictions.eq("code", code)).uniqueResult();
        if (object != null) {
            Province province = (Province)object;
            return province.getName();
        }
        return null;
    }
}
